package com.zzw.zim.common.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * redis配置

 * @author XiaoJie
 * @date 2025/06/03 10:21:10
 */
@Configuration
public class RedisConfig {
	@Bean
	public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer () {
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
		// objectMapper.setMixInResolver()
		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
		return jackson2JsonRedisSerializer;
	}

	@Bean
	public RedisTemplate<String, Object> redisTemplate (RedisConnectionFactory factory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		//key HashKey 使用 String 序列化
		template.setKeySerializer(RedisSerializer.string());
		template.setHashKeySerializer(RedisSerializer.string());

		//value HashValue 使用 Jackson2JsonRedisSerializer 序列化
		// FastJson2JsonRedisSerializer<Object> fastJson2JsonRedisSerializer = new FastJson2JsonRedisSerializer<>(Object.class);
		template.setValueSerializer(jackson2JsonRedisSerializer());
		template.setHashValueSerializer(jackson2JsonRedisSerializer());

		template.setConnectionFactory(factory);
		return template;
	}
}
